<?php

require './includes/config.inc.php';
class JobPost
{
    // Allow access by all methods
    public $conn;
    // This is a magic method called automatically when class is used
    public function __construct()
    {
            $this->conn = new mysqli(DB_HOST,DB_USER,DB_PASS,DB_NAME)
                    or die('I\'m sorry but the server has failed. Please check back soon!');
    }

    public function getCategories($page,$inputID)
    {
        $sql = 'SELECT id, name FROM job_categories WHERE active = 1;';

        if($stmt = $this->conn->prepare($sql))
        {
            $stmt->execute();
            $stmt->bind_result($id, $name);
            if($page == 'home')
            {
                $text = '<option value="0">Search All Categories</option>';
            }
            else
            {
                $text = '<option value="">--- SELECT ONE ---</option>';
            }
            $select = '<label for="jobCat">Job Category: </label>
                        <select name="jobCat" id="jobCat" class="jobPosting">';
            $select .= $text;

            while ($stmt->fetch()) {
				if($inputID == $id) {
                $select .= '<option value='.$id.' selected="true">'.$name.'</option>';
				}
				else {
				$select .= '<option value='.$id.'>'.$name.'</option>';
				}
            }

            $select .= '</select>';

            return $select;
        }
        else
        {
            return false;
        }
    }
	
	public function saveLastSearch($country,$state,$city,$jobCat)
	{
		$sql = "UPDATE last_search 
				SET country = ?, 
					state = ?, 
					city = ?, 
					jobCat = ?
				WHERE id = '1' ";
		if($stmt = $this->conn->prepare($sql))
		{
           $stmt->bind_param('iisi',$country,$state,$city,$jobCat);
           $stmt->execute();
		   $stmt->close();
		}
		else
		{
			return 'ERROR! Last Search Not Updated!';
		}
	}
	
	public function getLastSearch()
	{
		$sql = 'SELECT country
					  ,state
					  ,city
					  ,jobCat
			    FROM last_search
				WHERE id = 1';
		if($stmt = $this->conn->prepare($sql))
		{
			$stmt->execute();
			$stmt->bind_result($country,$state,$city,$jobCat);
			$stmt->fetch();
			$lastSearch = array(  'country'=>$country,
                                    'state'=>$state,
                                     'city'=>$city,
								   'jobCat'=>$jobCat);
			return $lastSearch;
		}
		else
		{
			return 'ERROR! Could Not Get Last Search From DataBase';
		}
	}

    public function getCategoryName($catID)
    {
        $sql = 'SELECT name FROM job_categories WHERE id = '.$catID.';';
        if($stmt = $this->conn->prepare($sql))
        {
            $stmt->execute();
            $stmt->bind_result($catName);
            $stmt->fetch();
            return $catName;
        }
        else
        {
            return 'ERROR! Please try again!';
        }
    }

    public function getCountries()
    {
        $sql = 'SELECT id, name FROM countries;';

        if($stmt = $this->conn->prepare($sql))
        {
            $stmt->execute();
            $stmt->bind_result($id, $name);
            $select = '<label for="country">Country: </label>
                        <select name="country" id="country" class="jobPosting">
                            <option value="">-- SELECT ONE --</option>';

            while ($stmt->fetch()) {
					$select .= '<option value='.$id.'>'.$name.'</option>';
            }

            $select .= '</select>';

            return $select;
        }
        else
        {
            return false;
        }
    }
	
	public function getCountryName($id)
    {
        $sql = 'SELECT name FROM countries WHERE id = ?;';

        if($stmt = $this->conn->prepare($sql))
        {
			$stmt->bind_param('i',$id);
            $stmt->execute();
            $stmt->bind_result($name);
			if($stmt->fetch())
            {
                return $name;
            }
            else
            {
                return 'ERROR';
            }
		}
		else
		{
			return false;
		}
    }

    public function getStates($countryID)
    {
        $sql = 'SELECT id, name FROM states WHERE countryID = '.$countryID.';';

        if($stmt = $this->conn->prepare($sql))
        {
            $stmt->execute();
            $stmt->bind_result($id, $name);
            
            $select = '';
            while ($stmt->fetch()) {
                $select .= '<option value='.$id.'>'.$name.'</option>';
            }
            
            $stmt->close();
            $message['message'] = $select;
            $message['error'] = false;
            return json_encode($message);
        }
        else
        {
            return false;
        }
    }
	
	 public function getStatesList($countryID)
    {
        $sql = 'SELECT id, name FROM states WHERE countryID = '.$countryID.';';

        if($stmt = $this->conn->prepare($sql))
        {
            $stmt->execute();
            $stmt->bind_result($id, $name);
            $select = '<label for="state">State: </label>
                        <select name="state" id="state" class="statePosting">
                            <option value="">-- SELECT ONE --</option>';

            while ($stmt->fetch()) {
					$select .= '<option value='.$id.'>'.$name.'</option>';
            }

            $select .= '</select>';

            return $select;
        }
        else
        {
            return false;
        }
    }
	

    public function submitPost($postArray)
    {
        $employerID = $postArray[0];
        $jobTitle = $postArray[1];
        $jobCatID = $postArray[2];
        $jobDesc = $postArray[3];
        $salary = $postArray[4];
        $hideName = $postArray[5];
        $hideSalary = $postArray[6];
        $country = $postArray[7];
        $state1 = $postArray[8];
        $state2 = $postArray[9];
        $state3 = $postArray[10];
        $state4 = $postArray[11];
        $state5 = $postArray[12];
        $city1 = $postArray[13];
        $city2 = $postArray[14];
        $city3 = $postArray[15];
        $city4 = $postArray[16];
        $city5 = $postArray[17];

        $sql = "INSERT INTO job_posts(employerID,
                                        title,
                                        catID,
                                        description,
                                        salary,
                                        country,
                                        displayName,
                                        displaySalary,
                                        postDate) VALUES (?,?,?,?,?,?,?,?,CURDATE())";

        if($stmt = $this->conn->prepare($sql))
        {
            $stmt->bind_param('isisssii', $employerID, $jobTitle, $jobCatID, $jobDesc, $salary, $country,  $hideName, $hideSalary);
            $stmt->execute();
            $jobPostID = $stmt->insert_id;
            $sqlLocation = "INSERT INTO job_locations(jobID, city, state) VALUES (?,?,?)";
            $stmt->close();

            for ($i=1; $i<=5; $i++)
            {
                if(${'state'.$i} != '' && ${'city'.$i} != '')
                {
                    if($stmt = $this->conn->prepare($sqlLocation))
                    {
                        $stmt->bind_param('iss', $jobPostID, ${'city'.$i}, ${'state'.$i});
                        $stmt->execute();
                        $stmt->close();
                    }
                }
            }

            $message = array();
            $message['error'] = false;
            $message['message'] = 'Your job post has been submitted successfully!  You will now be redirected to the My Account page.';
            return json_encode($message);
        }
        else
        {
                $message['error'] = true;
                $message['message'] = "Hmm, a weird error occurred, please try again!";
                return json_encode($message);
        }
    }

    public function getEmployerPosts($employerID)
    {
        $sql = 'SELECT id, title, postDate
                    FROM job_posts
                    WHERE employerID = ?
					AND deleted = 0
                    AND postDate >= (NOW() - INTERVAL 90 DAY) 
                    ORDER BY id DESC;';

        if($stmt = $this->conn->prepare($sql))
        {
            $stmt->bind_param('s',$employerID);
            $stmt->execute();
            $stmt->bind_result($id, $title, $postDate);
            $collectJobs = array();
            while ($stmt->fetch()) {
                $jobArray = array(  'id'=>$id,
                                    'title'=>$title,
                                    'postDate'=>$postDate);
                array_push($collectJobs, $jobArray);
            }
            return $collectJobs;
        }
        else
        {
            return false;
        }
    }

    public function getExpiredEmployerPosts($employerID)
    {
        $sql = 'SELECT id, title, postDate
                    FROM job_posts
                    WHERE employerID = ?
					AND deleted = 0
                    AND postDate <= (NOW() - INTERVAL 90 DAY)
                    ORDER BY id DESC;';

        if($stmt = $this->conn->prepare($sql))
        {
            $stmt->bind_param('s',$employerID);
            $stmt->execute();
            $stmt->bind_result($id, $title, $postDate);
            $collectJobs = array();
            while ($stmt->fetch()) {
                $jobArray = array(  'id'=>$id,
                                    'title'=>$title,
                                    'postDate'=>$postDate);
                array_push($collectJobs, $jobArray);
            }
            return $collectJobs;
        }
        else
        {
            return false;
        }
    }

    public function getSearchPosts($country, $state, $city, $cat)
    {
        $select = '';
        if($cat != 0){ $select .= ' AND job_posts.catID = '.$cat; }
        /*$sql = 'SELECT id, title, postDate from job_posts WHERE country = '.$country.$select;*/
        
        if($city != ''){ $select .= " AND job_locations.city LIKE '%".$city."%'"; }

        $sql = 'SELECT DISTINCT job_posts.id, job_posts.title, job_posts.postDate, job_posts.catID
                    FROM job_posts LEFT JOIN job_locations
                    ON job_posts.id = job_locations.jobID
                    WHERE job_posts.country = '.$country.'
                    AND job_posts.postDate >= (NOW() - INTERVAL 90 DAY)
                    AND job_locations.state = '.$state.' '.$select.';';

        if($stmt = $this->conn->prepare($sql))
        {
            $stmt->execute();
            $stmt->bind_result($id, $title, $postDate, $catID);
            $collectJobs = array();
            while ($stmt->fetch()) {
                $jobArray = array(  'id'=>$id,
                                    'title'=>$title,
                                    'postDate'=>$postDate,
                                    'catID'=>$catID);
                array_push($collectJobs, $jobArray);
            }
            return $collectJobs;

        }
        else
        {
            return 'ERROR! Please try again!';
        }
    }
	
	/*DeActivate Specific User Post*/
	public function removeOnePost($postId)
	{
		$sql = "UPDATE job_posts
				SET deleted = 1 
				WHERE id = ? ";
		if($stmt = $this->conn->prepare($sql))
		{
           $stmt->bind_param('i',$postId);
           $stmt->execute();
		   $stmt->close();
		   	require_once 'classes/Login.php';
    		$Login = new Login();
			/*include 'includes/header.inc.php';*/
			header('location:myEmployers.php');
			/*include 'includes/footer.inc.php';*/
		}
		else
		{
			return 'ERROR! User Post not Deleted!';
		}
	}

    public function getStateName($stateID)
    {
        $sql = 'SELECT name FROM states WHERE id = ?;';

        if($stmt = $this->conn->prepare($sql))
        {
            $stmt->bind_param('i',$stateID);
            $stmt->execute();
            $stmt->bind_result($name);
            if($stmt->fetch())
            {
                return $name;
            }
            else
            {
                return 'ERROR';
            }
        }
        else
        {
            return false;
        }
    }

    public function getPost($jobID,$emp)
    {
        if($emp != 0)
        {
            $sql = 'SELECT employerID, title, catID, description, salary, country, displayName, displaySalary, postDate
                FROM job_posts WHERE id = ?
                ;'; //AND employerID = '.$emp.'
        }
        else
        {
            $sql = 'SELECT employerID, title, catID, description, salary, country, displayName, displaySalary, postDate
                FROM job_posts WHERE id = ?
                AND postDate >= (NOW() - INTERVAL 90 DAY);';
        }
        

        if($stmt = $this->conn->prepare($sql))
        {
            $stmt->bind_param('i',$jobID);
            $stmt->execute();
            $stmt->bind_result($employerID, $title, $catID, $description, $salary, $country, $displayName, $displaySalary, $postDate);
            if($stmt->fetch())
            {

                $jobArray = array($employerID, $title, $catID, $description, $salary, $country, $displayName, $displaySalary, $postDate);

                return $jobArray;
            }
            else
            {
                return 'ERROR';
            }
        }
        else
        {
            return false;
        }
    }

    public function getLocations($jobID)
    {
        $sql = 'SELECT id, city, state FROM job_locations WHERE jobID = ?;';

        if($stmt = $this->conn->prepare($sql))
        {
            $stmt->bind_param('i',$jobID);
            $stmt->execute();
            $stmt->bind_result($id, $city, $state);
            $locations = array();
            while ($stmt->fetch()) {
                $location = array($id, $city, $state);
                array_push($locations, $location);
            }
            return $locations;
        }
        else
        {
            return false;
        }
    }
	
	public function getCategoriesEdit()
    {
        $sql = 'SELECT id, name FROM job_categories WHERE active = 1;';

        if($stmt = $this->conn->prepare($sql))
        {
            $stmt->execute();
<<<<<<< .mine
            $stmt->bind_result($id, $name);
            $categories = array();
            while ($stmt->fetch()) {
                $category = array($id, $name);
                array_push($categories, $category);
=======
            $stmt->bind_result($employerID, $title, $catID, $description, $salary, $country, $displayName, $displaySalary);
            if($stmt->fetch())
            {
                $jobArray = array($employerID, $title, $catID, $description, $salary, $country, $displayName, $displaySalary, $postDate);

                $sqlInsert = "INSERT INTO job_posts(employerID,
                                title,
                                catID,
                                description,
                                salary,
                                country,
                                displayName,
                                displaySalary,
                                postDate) VALUES (".$jobArray[0].",'".$jobArray[1]."','".$jobArray[2]."','".$jobArray[3]."','".$jobArray[4]."',".$jobArray[5].",".$jobArray[6].",".$jobArray[7].",CURDATE());";
                if($stmt = $this->conn->prepare($sqlInsert))
                {
                    $stmt->execute();
                    $jobPostID = $stmt->insert_id;
                    $stmt->close();
                    return $jobPostID;
                }
                else
                {
                    return $sqlInsert;
                }
>>>>>>> .r35
            }
            return $categories;
        }
        else
        {
            return false;
        }
    }

    public function repostJob($id)
    {
		var_dump($id);
		$sql = "UPDATE job_posts
				SET postDate = CURDATE() 
				WHERE id = ? ";
		if($stmt = $this->conn->prepare($sql))
		{
           $stmt->bind_param('i',$id);
           $stmt->execute();
		   $stmt->close();
		   	require_once 'classes/Login.php';
    		$Login = new Login();
			/*include 'includes/header.inc.php';*/
			header('location:myPostings.php');
			/*include 'includes/footer.inc.php';*/
		}
		else
		{
			return 'ERROR! User Post not Deleted!';
		}
    }

    public function __destruct()
    {
            // Close the connection, return true if successful
            $closeConnection = $this->conn->close();
            if($closeConnection){return true;}
    }
}
?>